package icu.sehnen.zuul.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import icu.sehnen.common.result.CommonResult;
import icu.sehnen.common.result.Permission;
import icu.sehnen.zuul.feign.UserFeign;
import icu.sehnen.zuul.util.JwtTokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;

@Component
public class PermissionFilter extends ZuulFilter {

//    @Value("#{'${pathlist}'.split(',')}")
//    private List<String> pathlist;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserFeign userFeign;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletResponse response = requestContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        HttpServletRequest request = requestContext.getRequest();
        String uri = request.getRequestURI();
        //那些路径可以直接放行
//       白名单配置
//      boolean a  =  pathlist.stream().anyMatch(path-> StringUtils.contains(uri,path));
//todo        查询所有权限看是否访问路径是否在所有的权限路径中，然后判断该用户是否有权限。
//        查询用户的所有权限
           List<Permission> permissionList =userFeign.getPermission().getData();
        boolean a  =  permissionList.stream().anyMatch(permission -> StringUtils.contains(uri,permission.getPath()));
        if (a){
            return null;
        }

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isBlank(authorization)){

            CommonResult result = CommonResult.forbidden("没有获取到token");
            JsonMapper jsonMapper=new JsonMapper();
            String jsonStr = jsonMapper.writeValueAsString(result);
            requestContext.setResponseBody(jsonStr);
            requestContext.setSendZuulResponse(false);
            return null;
        }
        String token = StringUtils.substring(authorization,"bearer".length()).trim();
        
        // 第二种方法：远程调用验证(复杂的认证)
     checkLongRange(token,requestContext,uri);

        return null;
    }


    // 第二种方法：远程调用验证(复杂的认证)
    private Object checkLongRange(String token, RequestContext requestContext, String uri) throws JsonProcessingException {
        try {
            boolean tokenExpired = jwtTokenUtil.isTokenExpired(token);
            if (tokenExpired){
               CommonResult result= CommonResult.forbidden("token 过期");
                JsonMapper jsonMapper=new JsonMapper();
                String jsonStr = jsonMapper.writeValueAsString(result);
                requestContext.setResponseBody(jsonStr);
                requestContext.setSendZuulResponse(false);
                return null;
            }
        } catch (Exception e) {
            // 处理token过期
            if(e instanceof ExpiredJwtException){
                CommonResult.forbidden("token 过期");
                JsonMapper jsonMapper=new JsonMapper();
                String jsonStr = jsonMapper.writeValueAsString(jsonMapper);
                requestContext.setResponseBody(jsonStr);
                requestContext.setSendZuulResponse(false);
                return null;
            }
            e.printStackTrace();
        }

        CommonResult commonResult = userFeign.checkAccessToUri(uri, jwtTokenUtil.getUserNameFromToken(token));
        if (commonResult.getCode() == 200){
            return null;
        } else if (commonResult.getCode() == 500){
            CommonResult result=CommonResult.forbidden("您没有权限");
            JsonMapper jsonMapper=new JsonMapper();
            String jsonStr = jsonMapper.writeValueAsString(result);
            requestContext.setResponseBody(jsonStr);
            requestContext.setSendZuulResponse(false);
            return null;
        }
        return null;
    }
   
}